<template>
  <div>
    <el-card style="width: 100%; height: 100%">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">物料管理</el-breadcrumb-item>
        <el-breadcrumb-item>物料管理</el-breadcrumb-item>
        <el-breadcrumb-item>物料信息管理</el-breadcrumb-item>
        <el-breadcrumb-item>新增物料</el-breadcrumb-item>
      </el-breadcrumb>
    </el-card>
    
    <el-card style="width: 100%; height: 100%; margin-top: 5px">
      <div class="page-header">
        <h2>新增物料</h2>
        <div class="header-actions">
          <el-button type="info" @click="handleBasicInfo">基础信息</el-button>
        </div>
      </div>
      
      <el-form
        ref="formRef"
        :model="formModel"
        :rules="rules"
        label-width="120px"
        class="material-form"
      >
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="物料编号" prop="materialCode">
              <el-input 
                v-model="formModel.materialCode" 
                placeholder="请输入" 
                clearable
                :disabled="autoGenerateCode"
              />
              <div class="form-item-extra">
                <el-switch 
                  v-model="autoGenerateCode" 
                  active-text="系统编号"
                  inactive-text=""
                  @change="handleCodeGenerate"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" prop="materialName">
              <el-input 
                v-model="formModel.materialName" 
                placeholder="请输入" 
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="规格型号" prop="specification">
              <el-input 
                v-model="formModel.specification" 
                placeholder="请输入" 
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-select 
                v-model="formModel.unit" 
                placeholder="请选择单位"
                clearable
                style="width: 100%"
              >
                <el-option label="个" value="个" />
                <el-option label="台" value="台" />
                <el-option label="套" value="套" />
                <el-option label="件" value="件" />
                <el-option label="米" value="米" />
                <el-option label="千克" value="千克" />
                <el-option label="升" value="升" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="物料类型" prop="materialType">
              <el-select 
                v-model="formModel.materialType" 
                placeholder="请选择物料类型"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in materialTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料属性" prop="materialAttribute">
              <el-select 
                v-model="formModel.materialAttribute" 
                placeholder="请选择物料属性"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in materialAttributeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="物料分类" prop="materialCategory">
              <el-select 
                v-model="formModel.materialCategory" 
                placeholder="请选择物料分类"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in materialCategoryOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formModel.status">
                <el-radio :label="true">启用</el-radio>
                <el-radio :label="false">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="有效期限" prop="materialDays">
              <div style="display: flex; align-items: center; gap: 8px">
                <el-input-number 
                  v-model="formModel.materialDays" 
                  :min="0" 
                  placeholder="请输入"
                  :disabled="!enableExpiry"
                  style="flex: 1"
                />
                <span>天</span>
                <el-checkbox v-model="enableExpiry" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="报警天数" prop="materialStopDays">
              <div style="display: flex; align-items: center; gap: 8px">
                <span>提前</span>
                <el-input-number 
                  v-model="formModel.materialStopDays" 
                  :min="0" 
                  placeholder="请输入"
                  style="flex: 1"
                />
                <span>天报警</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="库存上限" prop="materialUpper">
              <el-input-number 
                v-model="formModel.materialUpper" 
                :min="0" 
                placeholder="请输入"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存下限" prop="materialDown">
              <el-input-number 
                v-model="formModel.materialDown" 
                :min="0" 
                placeholder="请输入"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="采购价格" prop="materialMoney">
              <el-input-number 
                v-model="formModel.materialMoney" 
                :min="0" 
                :precision="2" 
                placeholder="请输入"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formModel.remark"
            type="textarea"
            :rows="4"
            placeholder="请输入"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <!-- 图片上传区域 -->
      <el-divider />
      <div style="margin: 20px 0">
        <h3 style="margin: 0 0 15px 0">图片</h3>
        <div style="display: flex; gap: 15px; align-items: flex-start">
          <el-button type="primary" @click="triggerImageUpload">上传图片</el-button>
          <input
            ref="imageInputRef"
            type="file"
            accept="image/*"
            style="display: none"
            @change="handleImageChange"
          />
          <div
            v-if="imagePreview"
            style="position: relative; display: inline-block"
          >
            <el-image
              :src="imagePreview"
              style="width: 150px; height: 150px; border: 1px dashed #dcdfe6; border-radius: 4px"
              fit="cover"
            />
            <el-button
              type="danger"
              size="small"
              circle
              style="position: absolute; top: -10px; right: -10px"
              @click="removeImage"
            >
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
          <div
            v-else
            style="
              width: 150px;
              height: 150px;
              border: 1px dashed #dcdfe6;
              border-radius: 4px;
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              cursor: pointer;
              color: #909399;
            "
            @click="triggerImageUpload"
          >
            <el-icon style="font-size: 40px; margin-bottom: 8px"><Plus /></el-icon>
            <span>上传图片</span>
          </div>
        </div>
      </div>
      
      <!-- 附件上传区域 -->
      <el-divider />
      <div style="margin: 20px 0">
        <h3 style="margin: 0 0 15px 0">附件</h3>
        <el-upload
          ref="fileUploadRef"
          :auto-upload="false"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
          :file-list="fileList"
          drag
          style="width: 100%"
        >
          <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
          <div class="el-upload__text">
            点击或者拖动文件到虚线框内上传
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持 docx, xls, PDF, rar, zip, PNG, JPG 等类型的文件
            </div>
          </template>
        </el-upload>
      </div>
      
      <div style="margin-top: 30px; text-align: right">
        <el-button @click="handleCancel">关闭</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ArrowRight, Plus, Close, UploadFilled } from "@element-plus/icons-vue";
import https from "@/Http/http";
import { reactive, ref } from "vue";
import { ElMessage, type FormInstance, type FormRules, type UploadFile } from "element-plus";
import { useRouter } from "vue-router";

const router = useRouter();

// 写库 API 使用统一的 https.Writes 实例

// 表单数据接口
interface MaterialForm {
  id: number;
  materialCode: string;
  materialName: string;
  specification: string;
  unit: string;
  materialType: number | null;
  materialAttribute: number | null;
  materialCategory: number | null;
  status: boolean;
  remark: string;
  materialDays: number;
  materialStopDays: number;
  materialUpper: number;
  materialDown: number;
  materialMoney: number;
}

// API响应接口
interface ApiResultResponse<T> {
  code: number;
  msg: string;
  data: T;
}

const formRef = ref<FormInstance>();
const imageInputRef = ref<HTMLInputElement>();
const fileUploadRef = ref();
const autoGenerateCode = ref(false);
const enableExpiry = ref(false);
const submitLoading = ref(false);

// 图片预览
const imagePreview = ref("");
const uploadedImageUrl = ref("");

// 文件列表
const fileList = ref<UploadFile[]>([]);
const uploadedFileUrl = ref("");

const defaultFormModel: MaterialForm = {
  id: 0,
  materialCode: "",
  materialName: "",
  specification: "",
  unit: "",
  materialType: null,
  materialAttribute: null,
  materialCategory: null,
  status: true,
  remark: "",
  materialDays: 0,
  materialStopDays: 0,
  materialUpper: 0,
  materialDown: 0,
  materialMoney: 0,
};

const formModel = reactive<MaterialForm>({ ...defaultFormModel });

// 物料类型选项
const materialTypeOptions = [
  { label: "类型一", value: 1 },
  { label: "类型二", value: 2 },
  { label: "类型三", value: 3 },
];

// 物料属性选项
const materialAttributeOptions = [
  { label: "自制", value: 1 },
  { label: "外购", value: 2 },
];

// 物料分类选项
const materialCategoryOptions = [
  { label: "分类一", value: 1 },
  { label: "分类二", value: 2 },
  { label: "分类三", value: 3 },
];

// 表单验证规则
const rules = reactive<FormRules>({
  materialCode: [{ required: true, message: "物料编号不可为空", trigger: "blur" }],
  materialName: [{ required: true, message: "物料名称不可为空", trigger: "blur" }],
  specification: [{ required: true, message: "规格型号不可为空", trigger: "blur" }],
  unit: [{ required: true, message: "单位不可为空", trigger: "change" }],
  materialType: [{ required: true, message: "请选择物料类型", trigger: "change" }],
  materialAttribute: [{ required: true, message: "请选择物料属性", trigger: "change" }],
  materialCategory: [{ required: true, message: "请选择物料分类", trigger: "change" }],
});

// 将前端表单数据转换为后端请求格式
const formToRequest = (form: MaterialForm) => {
  return {
    id: form.id || 0,
    MaterialCard: form.materialCode,
    MaterialName: form.materialName,
    MaterialModelSame: form.specification,
    MaterialUnit: form.unit,
    MaterialTypeId: form.materialType || 0,
    MaterialAttributeId: form.materialAttribute || 0,
    MaterialClassificationId: form.materialCategory || 0,
    MaterialState: form.status,
    MaterialDays: enableExpiry.value ? form.materialDays || 0 : 0,
    MaterialStopDays: form.materialStopDays || 0,
    MaterialUpper: form.materialUpper || 0,
    MaterialDown: form.materialDown || 0,
    MaterialMoney: form.materialMoney || 0,
    MaterialDes: form.remark || "",
    MaterialPhoto: uploadedImageUrl.value || "",
    MaterialFile: uploadedFileUrl.value || "",
  };
};

// 生成系统编号
const generateSystemCode = () => {
  const timestamp = Date.now();
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
  return `MAT${timestamp}${random}`;
};

// 处理编号生成开关
const handleCodeGenerate = (value: boolean) => {
  if (value) {
    formModel.materialCode = generateSystemCode();
  } else {
    formModel.materialCode = "";
  }
};

// 基础信息按钮点击
const handleBasicInfo = () => {
  ElMessage.info("基础信息功能待实现");
};

// 触发图片上传
const triggerImageUpload = () => {
  imageInputRef.value?.click();
};

// 处理图片选择
const handleImageChange = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (!file) return;

  // 验证文件类型
  if (!file.type.startsWith("image/")) {
    ElMessage.error("请选择图片文件");
    return;
  }

  // 验证文件大小（例如：5MB）
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error("图片大小不能超过5MB");
    return;
  }

  // 预览图片
  const reader = new FileReader();
  reader.onload = (e) => {
    imagePreview.value = e.target?.result as string;
  };
  reader.readAsDataURL(file);

  // 上传图片
  try {
    const formData = new FormData();
    formData.append("file", file);

    const response = await https.Writes.post(`/MaterialAdd/UploadImgs`, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });

    if (response.data) {
      uploadedImageUrl.value = response.data;
      ElMessage.success("图片上传成功");
    }
  } catch (error) {
    console.error("图片上传失败:", error);
    ElMessage.error("图片上传失败，请稍后再试");
    imagePreview.value = "";
  }
};

// 移除图片
const removeImage = () => {
  imagePreview.value = "";
  uploadedImageUrl.value = "";
  if (imageInputRef.value) {
    imageInputRef.value.value = "";
  }
};

// 处理文件变化
const handleFileChange = async (file: UploadFile) => {
  const rawFile = file.raw;
  if (!rawFile) return;

  // 验证文件类型
  const fileExtension = rawFile.name.split(".").pop()?.toLowerCase();
  const allowedExtensions = ["docx", "xls", "xlsx", "pdf", "rar", "zip", "png", "jpg", "jpeg"];

  if (!allowedExtensions.includes(fileExtension || "")) {
    ElMessage.error("不支持的文件类型，请上传 docx, xls, PDF, rar, zip, PNG, JPG 等类型的文件");
    fileUploadRef.value?.handleRemove(file);
    return;
  }

  // 上传文件
  try {
    const formData = new FormData();
    formData.append("file", rawFile);

    const response = await https.Writes.post(`/MaterialAdd/UploadImgs`, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });

    if (response.data) {
      uploadedFileUrl.value = response.data;
      ElMessage.success("文件上传成功");
    }
  } catch (error) {
    console.error("文件上传失败:", error);
    ElMessage.error("文件上传失败，请稍后再试");
    fileUploadRef.value?.handleRemove(file);
  }
};

// 处理文件移除
const handleFileRemove = () => {
  uploadedFileUrl.value = "";
};

// 取消按钮
const handleCancel = () => {
  router.push("/material/list");
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }

    submitLoading.value = true;

    try {
      const requestData = formToRequest(formModel);
      
      const response = await https.Writes.post(
        `/MaterialAdd/MaterilAdd`,
        requestData
      );

      if (response.data.code === 1) {
        ElMessage.success(response.data.msg || "新增物料成功");
        router.push("/Material.GetList.vue");
      } else {
        ElMessage.error(response.data.msg || "新增物料失败");
      }
    } catch (error) {
      console.error("新增物料失败:", error);
      ElMessage.error("请求失败，请稍后再试");
    } finally {
      submitLoading.value = false;
    }
  });
};
</script>

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.page-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.material-form {
  max-width: 1000px;
}

.form-item-extra {
  margin-top: 5px;
}

.el-upload__tip {
  color: #606266;
  font-size: 12px;
  margin-top: 7px;
}
</style>